package com.wchat.utils;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wchat.bean.entity.Users;
import com.wchat.config.GlobalKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Objects;

/**
 * @author : willian fu
 * @date : 2019/12/11
 */
@Component
public class JwtUtil {

    private static final String key = "~@wchat*..";

    private static JWTVerifier jwtVerifier;

    private final int JWT_TOKEN_EXPIRE = 0;

    private final static String JWT_TOKEN_HEADER = "Authorization";

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 创建token令牌
     * @param user 待加密的用户信息
     * @return jwt token
     */
    public String jwtGetToken(Users user) {
        String token= JWT.create()
                .withAudience(String.valueOf(user.getUserId()), user.getUserName())
                //.withExpiresAt(new Date(System.currentTimeMillis() + GlobalShareConfig.JWT_TOKEN_EXPIRE * 60000))
                .sign(Algorithm.HMAC256(key));
        return token;
    }

    /**
     * 刷新token
     * @return
     */
    public String jwtRefreshToken() {
        Users user = this.jwtGetUser();
        if (user != null) {
            return this.jwtGetToken(user);
        }
        return null;
    }

    /**
     * jwt token校验
     * @param token token字符串
     * @return 校验是否成功
     */
    public boolean jwtVerify(String token){
        Users users = jwtGetUserByToken(token);
        if (null != users){
            return token.equals(redisTemplate.opsForHash().get(GlobalKey.TOKEN_KEY, users.getUserId().toString()));
        }
        return false;
    }

    /**
     * 从jwt token解析用户信息
     * @param token token字符串
     * @return 用户信息实体
     */
    public Users jwtGetUserByToken(String token){
        JWTVerifier jwtVerifier = this.getJwtVerifier();
        if (StrUtil.isBlank(token)){
            return null;
        }
        try {
            List<String> audience = jwtVerifier.verify(token).getAudience();
            if (audience.size() > 1){
                return Users.builder().userId(Integer.parseInt(audience.get(0)))
                        .userName(audience.get(1)).build();
            }
        } catch (JWTVerificationException e) {
            return null;
        }
        return null;
    }

    /**
     * 从jwt token解析用户信息
     * @return 用户信息实体
     */
    public Users jwtGetUser(){
        return this.jwtGetUserByToken(this.jwtGetToken());
    }

    public String jwtGetToken(){
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return jwtGetToken(request);
    }

    public String jwtGetToken(HttpServletRequest request){
        String token = request.getHeader(JWT_TOKEN_HEADER);
        token = StrUtil.isBlank(token) ? request.getParameter("token") : token;
        return token;
    }

    /**
     * 获取token剩余时间
     * @param token
     * @return 剩余时长s
     */
    public Long getTokenExpires(String token){
        JWTVerifier jwtVerifier = this.getJwtVerifier();
        try {
            return jwtVerifier.verify(token).getExpiresAt().getTime() - System.currentTimeMillis();
        } catch (Exception e) {
           return 0L;
        }
    }

    /**
     * 获取 JWTVerifier
     * @return
     */
    public JWTVerifier getJwtVerifier(){
        if (jwtVerifier == null){
            synchronized (JWTVerifier.class) {
                if (jwtVerifier == null) {
                    jwtVerifier = JWT.require(Algorithm.HMAC256(key)).build();
                }
            }
        }
        return jwtVerifier;
    }
}
